package com.document.controller;

import com.document.entity.DocumentTask;
import com.document.dto.DatasourceConnection;
import com.document.dto.TaskCreateRequest;
import com.document.entity.schema.DatabaseSchema;
import com.document.service.DatabaseMetadataService;
import com.document.service.DocumentGenerator;
import com.document.service.DocumentTaskService;
import com.document.vo.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/api/task")
@RequiredArgsConstructor
public class DocumentController {

    private final DocumentTaskService taskService;
    private final DatabaseMetadataService metadataService;
    private final DocumentGenerator documentGenerator;

    @PostMapping("/create")
    public ResponseEntity<ApiResponse<DocumentTask>> createDocumentTask(
            @RequestBody @Validated TaskCreateRequest request) {

        DocumentTask task;
        if (request.getConnection() != null) {
            task = taskService.createTask(request.getConnection(), null);
        } else {
            DatasourceConnection defaultConnection = new DatasourceConnection();
            defaultConnection.setDbType("mysql");
            task = taskService.createTask(defaultConnection, request.getSqlContent());
        }

        return ResponseEntity.ok(ApiResponse.success(task));
    }

    @GetMapping("/{taskId}")
    public ResponseEntity<ApiResponse<DocumentTask>> getTask(@PathVariable String taskId) {
        DocumentTask task = taskService.lambdaQuery()
                .eq(DocumentTask::getTaskId, taskId)
                .one();

        if (task == null) {
            return ResponseEntity.ok(ApiResponse.error("任务不存在"));
        }

        return ResponseEntity.ok(ApiResponse.success(task));
    }

    @GetMapping("/{taskId}/result")
    public ResponseEntity<String> getTaskResult(@PathVariable String taskId) {
        DocumentTask task = taskService.lambdaQuery()
                .eq(DocumentTask::getTaskId, taskId)
                .one();

        if (task == null || !"success".equals(task.getStatus())) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .contentType(MediaType.TEXT_HTML)
                .body(task.getResultHtml());
    }

    @GetMapping("/{taskId}/export")
    public ResponseEntity<byte[]> exportDocument(
            @PathVariable String taskId,
            @RequestParam String format) {

        DocumentTask task = taskService.lambdaQuery()
                .eq(DocumentTask::getTaskId, taskId)
                .one();

        if (task == null || !"success".equals(task.getStatus())) {
            return ResponseEntity.notFound().build();
        }

        byte[] content;
        String filename;
        MediaType mediaType;

        if ("md".equalsIgnoreCase(format)) {
            try {
                // 重新生成 Markdown 内容
                DatabaseSchema schema;
                if (task.getSqlContent() != null && !task.getSqlContent().isEmpty()) {
                    schema = taskService.parseSqlContent(task.getSqlContent());
                } else {
                    DatasourceConnection connection = taskService.decryptConnectionInfo(task.getConnectionInfo());
                    schema = metadataService.parseSchema(connection);
                }

                String markdownContent = documentGenerator.generateMarkdown(schema);
                content = markdownContent.getBytes(StandardCharsets.UTF_8);
                filename = "database_document.md";
                mediaType = MediaType.TEXT_PLAIN;

            } catch (Exception e) {
                log.error("生成Markdown文档失败", e);
                // 如果生成失败，返回错误信息
                String errorContent = "# 数据库文档\n\n> 生成Markdown文档时发生错误: " + e.getMessage();
                content = errorContent.getBytes(StandardCharsets.UTF_8);
                filename = "database_document.md";
                mediaType = MediaType.TEXT_PLAIN;
            }
        } else {
            // HTML 导出保持不变
            content = task.getResultHtml().getBytes(StandardCharsets.UTF_8);
            filename = "database_document.html";
            mediaType = MediaType.TEXT_HTML;
        }

        return ResponseEntity.ok()
                .contentType(mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(content);
    }
}